﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;

public partial class Templates_StoreLocator_Default : Acms.AcmsControls.TemplatePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            EnsureStoresOrganised();
            System.Text.StringBuilder tmpJavascript = new System.Text.StringBuilder();
            tmpJavascript.Append("var stores = [];");
            var stores = new List<Acms.Bll.Post>();
            orgainsedStores.ForEach(x => stores.AddRange(x.Value));
            stores.ForEach((x, i) => tmpJavascript.AppendFormat("stores.push(new Store(\"{0}\",\"{1}\",{2}-0,{3}-0, \"{4}\"));", x.DisplayName, GetAddress(x, i), GetLat(x, i), GetLong(x, i), ResolveUrl(x is Acms.Bll.DummyPost ? "#" : x.Url)));
            JavascriptArray = tmpJavascript.ToString();
        }
    }

    private string GetLong(Acms.Bll.Post store, int i)
    {
        string retVal = null;
        if (store is Acms.Bll.DummyPost)
        {
            //generate a variable position
            retVal = (-2.5 + ((double)(i) * 0.2)).ToString();
        }
        else
        {
            var control = store.FindPostControl("Longitude");
            if (control != null)
            {
                var properties = control.GetProperties<Acms.AcmsControls.TextContentControlProperties>();
                if (properties != null)
                {
                    retVal = properties.Text.Replace("\n", "").Trim();
                }
            }
        }
        return retVal;
    }

    private string GetLat(Acms.Bll.Post store, int i)
    {
        string retVal = null;
        if (store is Acms.Bll.DummyPost)
        {
            //generate a variable position
            retVal = (51 + ((double)(i) * 0.2)).ToString();
        }
        else
        {
            var control = store.FindPostControl("Latitude");
            if (control != null)
            {
                var properties = control.GetProperties<Acms.AcmsControls.TextContentControlProperties>();
                if (properties != null)
                {
                    retVal = properties.Text.Replace("\n", "").Trim();
                }
            }
        }
        return retVal;
    }

    private string GetAddress(Acms.Bll.Post store, int index)
    {
        string retVal = null;
        if (store is Acms.Bll.DummyPost)
        {
            string[] addresses = new string[]{
                "Unit 2,<br/>Jackson’s Square Shopping Centre,<br/>11 Devoils Lane,<br/>Bishop Stortford CM23 3XH",
                "Unit 42,<br/>The Howard Centre,<br/>Welwyn Garden City<br/>AL8 6HA",
                "Unit 42,<br/>The Howard Centre,<br/>Welwyn Garden City<br/>AL8 6HA",
                "Unit 143,<br/>The Egale Centre,<br/>Derby DE21 2NQ",
                "Unit SU32,<br/>Highcross,<br/>LE1 4FP",
                "Kiosk 7,<br/>Broadmarsh Centre,<br/>Nottingham NG1 7LL",
                "Unit 60,<br/>Victoria Shopping Centre,<br/>Nottingham NG1 3QL",
                "Mall Kiosk 74,<br/>Lewisham Centre,<br/>Lewisham  SE13 7HB"
            };
            retVal = addresses[index % addresses.Length];
        }
        else
        {
            var addressControl = store.FindPostControl("Address");
            if (addressControl != null)
            {
                var properties = addressControl.GetProperties<Acms.AcmsControls.TextContentControlProperties>();
                if (properties != null)
                {
                    retVal = properties.Text.Replace("\n", "<br/>");
                }
            }
        }
        return retVal;
    }

    private string JavascriptArray
    {
        get { return ViewState["JavascriptArray"] as string; }
        set { ViewState["JavascriptArray"] = value; }
    }

    private Dictionary<Acms.Bll.Topic, List<Acms.Bll.Post>> orgainsedStores;
    private void EnsureStoresOrganised()
    {
        if(orgainsedStores == null)
        {
            orgainsedStores = new Dictionary<Acms.Bll.Topic,List<Acms.Bll.Post>>();
            var regions = Acms.Bll.Topic.GetAllBySiteIdAndTopicGroupPath(AcmsContext.SiteId, "Regions");
            foreach (var region in regions)
            {
                List<Acms.Bll.Post> stores = null;
                if(AcmsContext.CurrentPost != null)
                   stores = Acms.Bll.Post.GetAllByTopicIdAndParentPath(AcmsContext.SiteId, region.Id, "~/Stores", AcmsContext.SiteVersion);
                else
                    stores = Acms.Bll.DummyPost.CreateDummyList(3);
                orgainsedStores.Add(region, stores);
            }
        }
    }

    protected void dsRegions_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.Topic> e)
    {
        EnsureStoresOrganised();
        e.SetData(orgainsedStores.Keys);
    }

    protected void stores_DataBinding(object sender, EventArgs e)
    {
        Acms.WebControls.SimpleRepeater stores = sender as Acms.WebControls.SimpleRepeater;
        if (stores != null)
        {
            AjaxControlToolkit.AccordionContentPanel panel = stores.NamingContainer as AjaxControlToolkit.AccordionContentPanel;
            if (panel != null)
            {
                Acms.Bll.Topic region = panel.DataItem as Acms.Bll.Topic;
                if (region != null)
                {
                    EnsureStoresOrganised();
                    stores.DataSource = orgainsedStores[region];
                }
            }
        }
    }

    protected void stores_ItemDataBound(object sender, Acms.WebControls.ItemDataBoundEventArgs e)
    {
        Acms.Bll.Post post = e.Item.DataItem as Acms.Bll.Post;
        HyperLink storeLink = e.Item.FindControl("storeLink") as HyperLink;
        HtmlGenericControl address = e.Item.FindControl("address") as HtmlGenericControl;
        if (post != null && storeLink != null && address != null)
        {
            if (post is Acms.Bll.DummyPost)
                storeLink.NavigateUrl = "#";
            else
                storeLink.NavigateUrl = post.Url;

            address.InnerHtml = GetAddress(post, e.Item.ItemIndex);
            if (string.IsNullOrEmpty(address.InnerHtml))
            {
                address.Visible = false;
            }
        }
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        ClientScript.RegisterStartupScript(this.GetType(), "StoresArray", JavascriptArray, true);
    }
}
